package backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/26 16:26
 * https://leetcode-cn.com/problems/permutations/
 * 全排列
 */
public class Permute {

    static List<List<Integer>> result;
    static LinkedList<Integer> list;

    public List<List<Integer>> permute(int[] nums) {
        result = new ArrayList<>();
        list = new LinkedList<>();
        flag = new int[nums.length];
        backTracking1(nums);
        return result;
    }

    private void backTracking(int[] nums) {
        if (list.size() == nums.length) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!list.contains(nums[i])) {
                list.add(nums[i]);
                backTracking(nums);
                list.removeLast();
            }
        }
    }

    /**
     * 设置标志数组
     * @param nums
     */
    static int[] flag;
    private void backTracking1(int[] nums) {
        if (list.size() == nums.length) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                continue;
            }
            flag[i] = 1;
            list.add(nums[i]);
            backTracking1(nums);
            list.removeLast();
            flag[i] = 0;
        }
    }

    public static void main(String[] args) {

    }
}
